import torch


def reshape_fortran(x, shape):
    if len(x.shape) > 0:
        x = x.permute(*reversed(range(len(x.shape))))
    return x.reshape(*reversed(shape)).permute(*reversed(range(len(shape))))


def ten2mat(tensor, mode):
    return reshape_fortran(torch.moveaxis(tensor, mode, 0), (tensor.shape[mode], -1))


def SNN(matrix, p=1):
    _, sigma, _ = torch.svd(matrix, some=True)
    nuclear = torch.pow(torch.sum(torch.pow(sigma, p)), 1 / p)
    return nuclear